<template>
  <div class="loginContainer">
    <el-card header="欢迎使用通用后台管理系统">
      <el-form shadow="always"
        :model="formData"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        @keyup.enter.native="submitForm('ruleForm')"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="formData.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="formData.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >登录</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from "../api/auth";
import { setToken } from "../utils/auth";
export default {
  data() {
    return {
      formData: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.formData)
            .then((data) => {
              let res = data;
              console.log(res);
              if (res.code === 1000) {
                setToken(res.data.accessToken,res.data.refreshToken)
                this.$router.push('/')
              } else {
                this.$message({type:'error',message:res.msg});
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style>
.loginContainer {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #eeeeee;
  height: 100vh;
}
.loginContainer .el-card__body {
  width: 480px;
}
.loginContainer .el-card__header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
}
</style>